<script setup lang='ts'>
import { ref, onMounted, watch } from 'vue';

const props = withDefaults(defineProps<{
    modelValue?: number,
    readonly?: boolean,
    name?: string
}>(), { withUndefined: true, readonly: false, propertyName: '属性值' })

const emits = defineEmits(["update:modelValue"]);
const inputHandler = (e: any) => {
    emits('update:modelValue', Number(e.target.value))
}
const unit = ref('m')
const extent = ref()
watch(() => props.modelValue, (val) => {
    extent.value = Number(val?.toFixed(2))
}, { immediate: true })
onMounted(() => {
    if (props.name === '面积') {
        unit.value = 'm²'
    } else {
        unit.value = 'm'
    }
    extent.value = Number(props.modelValue?.toFixed(2))
})
const change = () => {
    if (unit.value === 'm²') {
        unit.value = 'km²'
        if (props.modelValue) {
            extent.value = (props.modelValue / 1000000).toFixed(2)
        }
    } else if (unit.value === 'km²') {
        unit.value = 'm²'
        extent.value = props.modelValue?.toFixed(2)
    } else if (unit.value === 'm') {
        unit.value = 'km'
        if (props.modelValue) {
            extent.value = (props.modelValue / 1000).toFixed(2)
        }
    } else if (unit.value === 'km') {
        unit.value = 'm'
        extent.value = props.modelValue?.toFixed(2)
    }
}
</script>

<template>
    <div class="readonly_flag">
        <template v-if="name !== '面积' && name !== '周长' && name !== '长度' && name !== '圆半径'">
            <input type="number" class="input_number" :disabled="readonly" :value="modelValue" @input="inputHandler($event)"
                :style="{ flex: 1, cursor: `${readonly ? 'no-drop' : 'default'}` }" />
        </template>
        <template v-else>
            <input type="number" class="input_number" :disabled="readonly" :value="extent"
                :style="{ flex: 1, cursor: `${readonly ? 'no-drop' : 'default'}` }" @input="inputHandler($event)" />
            <label :disabled="false" @click="change">{{
            unit }}</label>
        </template>

    </div>
</template>

<style scoped>
input {
    display: inline-block;
    width: 100%;
    height: 26px;
    background: rgba(28, 28, 29, 0.6);
    border-radius: 4px;
    border: 1px solid #3b3c40;
    margin-right: 0;
    color: rgba(230, 230, 230, 1);
    padding-left: 11px;
    box-sizing: border-box;
}

input:hover {
    border: 1px solid #2c68f7;
}

input:focus {
    border: 1px solid #2c68f7;
}

.readonly_flag {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-items: center;
}

/* .readonly_true {
    pointer-events: none;
    user-select: none;
} */

label {
    width: 30px;
    text-align: right;
    cursor: pointer;
    color: rgba(230, 230, 230, 1);
}

.input_number::-webkit-outer-spin-button,
.input_number::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

.input_number[type="number"] {
    -moz-appearance: textfield;
}
</style>
